/*   Copyright (C) 2008 by Tomasz Dubik                                    *
 *   tdubik@gmail.com                                                      *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include <QDebug>
#include <QHeaderView>
#include <QTreeWidgetItem>
#include <QTreeWidget>
#include <QTextTable>
#include <QPrinter>
#include <QPrintDialog>
#include <QKeyEvent>
#include <QMessageBox>
#include <QWidget>
#include <QSettings>
#include <QUrl>
#include <QProgressBar>
#include <QToolBar>
#include <QMenu>
#include <QMenuBar>
#include <QStatusBar>

#include <vector>

#include "mainwindowimpl.h"
#include "globals.h"
#include "common.h"
#include "actioncollection.h"
#include "settings.h"
#include "shortcuts.h"
#include "customprogresswidget.h"

MainWindowImpl::MainWindowImpl( QWidget * parent, Qt::WFlags f) 
    : QMainWindow(parent, f), m_bExit(false),m_qpContextMenu(NULL), m_MissEvent(false)
{
    createActions();
    createUI();
    
    m_qpContextMenu = new QMenu( tr("Context menu") , this );
    m_qpContextMenu->addAction(ActionCollection::get("add"));
    m_qpContextMenu->addAction(ActionCollection::get("edit"));
    m_qpContextMenu->addAction(ActionCollection::get("remove"));
    m_pTreeWidget->setContextMenuPolicy( Qt::CustomContextMenu );

    m_ftpHandler = new FtpHandler(this);    

    //load settings
	loadTreeConfigSettings();
	loadConfigSettings();
	loadUiSettings();
	initializeSystemTray();
	setConnections();
    m_pTaskContainer = new Tasks::TaskContainer();
    m_pTaskContainer->load("todo.xml");
    setTreeData();
    connect(m_pTreeWidget, SIGNAL( itemChanged ( QTreeWidgetItem*, int)), this, SLOT(treeItemChanged(QTreeWidgetItem*, int)));
}

MainWindowImpl::~MainWindowImpl()
{
	delete m_trayIcon;
	delete m_trayIconMenu;
	delete m_ftpHandler;
    delete m_pTaskContainer;
}

void MainWindowImpl::createActions() {
    Shortcuts::addShortcut( ActionCollection::add( "add" , tr("&Add") , QIcon( ":/ui/add.png" ) , NULL ), "add" ) ; 
    ActionCollection::add( "edit" , tr("&Edit") , QIcon( ":/ui/edit.png" ) , NULL ) ;
    ActionCollection::add( "remove" , tr("&Remove") , QIcon( ":/ui/remove.png" ) , NULL ) ;
    ActionCollection::add( "configure" , tr("&Configure") , QIcon( ":/ui/config.png" ) , NULL ) ;
    ActionCollection::add( "synchronize", tr("&Synchronize"), QIcon( ":ui/sync.png" ), NULL );
    Shortcuts::addShortcut( ActionCollection::add( "hide",tr("&Hide"),QIcon(":/ui/hide.png"), m_trayIconMenu), "hide");
    Shortcuts::addShortcut( ActionCollection::add( "restore",tr("&Restore"),QIcon(":/ui/hide.png"), NULL), "restore");
    Shortcuts::addShortcut( ActionCollection::add( "quit",tr("&Quit"),QIcon(":/ui/quit.png"), NULL ), "quit") ;
    ActionCollection::add( "about" , tr("&About" ) , QIcon( ":/ui/main.png" ) , NULL ) ;
    ActionCollection::add( "aboutQT" , tr("About Qt") , QIcon( ":/ui/qt.png" ) , NULL ) ;
}

void MainWindowImpl::createUI() {
    // create toolbar 
    m_pToolBar = new QToolBar(tr("toolbar"),this);
    m_pToolBar->addAction( ActionCollection::get( "add" ) );
    m_pToolBar->addAction( ActionCollection::get( "edit" ) );
    m_pToolBar->addAction( ActionCollection::get( "remove" ) );
    m_pToolBar->addAction( ActionCollection::get( "configure" ) );
    m_pToolBar->addAction( ActionCollection::get( "synchronize" ));
    addToolBar(Qt::LeftToolBarArea, m_pToolBar);
    // create menus
    m_pFileMenu = new QMenu(tr("&File"),this);
    m_pFileMenu->addAction(ActionCollection::get("add"));
    m_pFileMenu->addAction(ActionCollection::get("edit"));
    m_pFileMenu->addAction(ActionCollection::get("hide"));
    m_pFileMenu->addAction(ActionCollection::get("quit"));
    m_pFileMenu->addAction(ActionCollection::get( "synchronize" ));
    m_pFileMenu->addAction(ActionCollection::get("configure"));
    
    m_pAboutMenu = new QMenu(tr("&About"),this);
    m_pAboutMenu->addAction( ActionCollection::get("about") );
    m_pAboutMenu->addAction( ActionCollection::get("aboutQT") );
    
    menuBar()->addMenu(m_pFileMenu);
    menuBar()->addMenu( m_pAboutMenu );
    
    // central/qtreewidget 
    m_pTreeWidget = new QTreeWidget(this);
    setView(m_pTreeWidget);
    setCentralWidget(m_pTreeWidget);
    setWindowIcon(QIcon(":/ui/main.png"));
    m_pTreeWidget->setMouseTracking(true);
}
//configure tree view
void MainWindowImpl::setView(QTreeWidget* tree)
{
    m_headers << tr("Tasks") << tr("Progress") << "ID";
	tree->setHeaderLabels( m_headers );
	QHeaderView* header = tree->header();
	header->setResizeMode( QHeaderView::Interactive );
	tree->setRootIsDecorated(true);
	tree->setSelectionBehavior( QAbstractItemView::SelectRows );
	tree->setSelectionMode(QAbstractItemView::SingleSelection);
	tree->setAlternatingRowColors( true );
    //tree->hideColumn(KTaskIDColumn);
}

CustomProgressWidget* MainWindowImpl::constructItemWidget(const QTreeWidgetItem& item, int value)
{
    CustomProgressWidget* widget = new CustomProgressWidget(item.text(KTaskIDColumn).toInt(), this, this );
    widget->resize(item.sizeHint(KTaskProgressColumn));
    widget->setValue(value);
    return widget;
}

void MainWindowImpl::setTreeData()
{
    Tasks::Task::Vector data = m_pTaskContainer->TasksData();
    Tasks::Task::Vector::iterator it = data.begin();
    int i = 0;
    int count = 0;
    QTreeWidgetItem* topLevelItem = NULL;
    while( it != data.end())
    {
        topLevelItem = new QTreeWidgetItem(m_pTreeWidget);
        topLevelItem->setText(KTaskTextColumn, QString::fromStdString((*it)->text()));
        topLevelItem->setFlags(topLevelItem->flags() | Qt::ItemIsEditable );
        topLevelItem->setSizeHint(KTaskProgressColumn, QSize(100, KRowHeight));
        //m_pTreeWidget->setItemWidget(topLevelItem,KTaskProgressColumn,(*it)->progress());        
        topLevelItem->setText(KTaskIDColumn, QString::number((*it)->id()));
        m_pTreeWidget->setItemWidget(topLevelItem, KTaskProgressColumn,constructItemWidget(*topLevelItem, (*it)->progress()));
        m_pTreeWidget->addTopLevelItem(topLevelItem);
        count = (*it)->childCount();
        for( i = 0; i<count; ++i)
            setTreeNode((*(*it)->child(i)), topLevelItem);
        ++it;
    }
}

void MainWindowImpl::setTreeNode( const Tasks::Task& newTask, QTreeWidgetItem* parentItem )
{
    qDebug() << Q_FUNC_INFO;
    qDebug() << newTask.id() << newTask.progress() << QString::fromStdString(newTask.text());
    QTreeWidgetItem* newItem = new QTreeWidgetItem(parentItem);
    newItem->setFlags(newItem->flags() | Qt::ItemIsEditable );
    newItem->setText( KTaskTextColumn, QString::fromStdString(newTask.text( )));
    newItem->setSizeHint(KTaskProgressColumn, QSize(100, KRowHeight));
    newItem->setText(KTaskIDColumn, QString::number(newTask.id()));
    m_pTreeWidget->setItemWidget(newItem, KTaskProgressColumn,constructItemWidget(*newItem, newTask.progress()));   
    parentItem->addChild(newItem);
    for(int i = 0; i < newTask.childCount(); ++i)
    {
        setTreeNode(*(newTask.child(i)), newItem );
    }
}

//set connection
void MainWindowImpl::setConnections()
{
	//menu action
	connect(ActionCollection::get("add"),SIGNAL(triggered()), this, SLOT(addTask()));
	connect(ActionCollection::get("edit"),SIGNAL(triggered()), this, SLOT(editTask()));
	connect(ActionCollection::get("remove"), SIGNAL(triggered()), this, SLOT(deleteTask()));
    connect(ActionCollection::get("aboutQT"), SIGNAL(triggered()), this, SLOT(aboutQt()));
    connect(ActionCollection::get("about"), SIGNAL(triggered()), this, SLOT(aboutQWhatToDo()));
    connect(ActionCollection::get("synchronize"), SIGNAL(triggered()), this, SLOT(synchronize()));
	connect(ActionCollection::get("quit"), SIGNAL(triggered()), this, SLOT(close()));
	connect(ActionCollection::get("configure"), SIGNAL(triggered()), this, SLOT(configureDlg()));

    connect( m_pTreeWidget , SIGNAL( customContextMenuRequested( const QPoint & ) ),this,SLOT( customContextMenuRequestedSlot( const QPoint & ) ) );

	//lists
	connect(m_pTreeWidget, SIGNAL( itemClicked (QTreeWidgetItem*,int )), this, SLOT(treeItemClicked(QTreeWidgetItem*,int )));
	connect(m_pTreeWidget, SIGNAL( itemActivated ( QTreeWidgetItem*,int)), this, SLOT(treeItemClicked(QTreeWidgetItem*,int )));
//    connect(m_pTreeWidget, SIGNAL( setTaskProgress(int, int)), this, SLOT(setTaskProgress(int,int)));
	connect(m_trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
	//ftp
	connect(m_ftpHandler, SIGNAL( ftpDone()), this, SLOT( ftpDone()));
	connect(m_ftpHandler, SIGNAL( ftpError(const QString&)), SLOT( ftpError(const QString&)));
    connect(m_ftpHandler, SIGNAL( ftpProgress(qint64, qint64)), SLOT( ftpProgress(qint64, qint64)));
}

void MainWindowImpl::loadConfigSettings()
{
    if( m_ftpHandler )
    {
        m_ftpHandler->setHost( Settings::value(SettingsKeys::AppSettings_FtpHost).toString());
        m_ftpHandler->setUsername(Settings::value(SettingsKeys::AppSettings_FtpUsername ).toString( ));
        m_ftpHandler->setPassword(Settings::value(SettingsKeys::AppSettings_FtpPassword ).toString( ));
        m_ftpHandler->setUsePassiveMode(Settings::value(SettingsKeys::AppSettings_FtpPassive ).toBool( ));
        m_savePassword = Settings::value(SettingsKeys::AppSettings_FtpSavePassword ).toBool( );
    }
}

void MainWindowImpl::saveConfigSettings()
{
    if( m_ftpHandler )
    {
        Settings::setValue(SettingsKeys::AppSettings_FtpHost, m_ftpHandler->host());
        Settings::setValue(SettingsKeys::AppSettings_FtpUsername, m_ftpHandler->username());
        Settings::setValue(SettingsKeys::AppSettings_FtpPassword, m_ftpHandler->password());
        Settings::setValue(SettingsKeys::AppSettings_FtpSavePassword, m_savePassword);
        Settings::setValue(SettingsKeys::AppSettings_FtpPassive, m_ftpHandler->usePassiveMode());
        Settings::sync();
    }
}

void MainWindowImpl::saveTreeConfigSettings()
{
	QHeaderView* header = m_pTreeWidget->header();
	Settings::setValue(SettingsKeys::UI_TREE_1_SIZE, header->sectionSize(0) );
	Settings::setValue(SettingsKeys::UI_TREE_2_SIZE, header->sectionSize(1) );
}

void MainWindowImpl::loadTreeConfigSettings()
{
	setSectionSize( 0, Settings::value( SettingsKeys::UI_TREE_1_SIZE ).toInt() );
	setSectionSize( 1, Settings::value( SettingsKeys::UI_TREE_2_SIZE ).toInt() );
}
//resice particular sections
void MainWindowImpl::setSectionSize(int section, int size)
{
	QHeaderView* header = m_pTreeWidget->header();
	if( size >= 0 )
        header->resizeSection(section,size);
}
//systray
void MainWindowImpl::initializeSystemTray()
{
	if( !QSystemTrayIcon::isSystemTrayAvailable() )
	{
		qDebug() << "No systemtray found";		
	}
	else
    {
		m_trayIcon = new QSystemTrayIcon(this);
		m_trayIconMenu = new QMenu(this);
		// actions
		connect(ActionCollection::get("hide"), SIGNAL(triggered()), this, SLOT(hide()));
		connect(ActionCollection::get("restore"), SIGNAL(triggered()), this, SLOT(showNormal()));
		connect(ActionCollection::get("quit"), SIGNAL(triggered()), this, SLOT(close()));
		m_trayIconMenu->addAction(ActionCollection::get("hide"));
		m_trayIconMenu->addAction(ActionCollection::get("restore"));
		m_trayIconMenu->addAction(ActionCollection::get("quit"));

		m_trayIcon->setContextMenu( m_trayIconMenu );
		m_trayIcon->setIcon( QIcon( ":/ui/main.png") );
		m_trayIcon->show();
	}
}

void MainWindowImpl::iconActivated(QSystemTrayIcon::ActivationReason reason)
{	
	if(reason != QSystemTrayIcon::Context)
	{
		if(this->isVisible())
			hide();
		else if(this->isHidden())
			showNormal();
	}
};

void MainWindowImpl::closeEvent(QCloseEvent * event)
{	
	qDebug() << m_bExit;
	if(! m_bExit )
	{
		event->ignore();
		hide();
	}
}

void MainWindowImpl::hideEvent(QHideEvent *event)
{	
	saveUiSettings();
}

void MainWindowImpl::showEvent(QShowEvent *event)
{	
	loadUiSettings();
};

void MainWindowImpl::close()
{
    qDebug() << Q_FUNC_INFO;
    m_bExit = true;
	QMainWindow::close();
}

//display configure dialog
void MainWindowImpl::configureDlg()
{
	ConfigDlgImpl* dialog = new ConfigDlgImpl(this);
	dialog->exec();
	if( dialog->result() == QDialog::Accepted )
    {
        //TODO: Use Settings class in Ftp handler instead settings data there;
		saveConfigSettings();
	}
}

//download taks from ftp
void MainWindowImpl::ftpDownload()
{
	if( m_ftpHandler )
	{
		m_ftpHandler->ftpDownload();
		statusBar()->showMessage(tr("Dowloading tasks config file from ftp"), 2000);
	}
}

//upload tasks

void MainWindowImpl::ftpUpload()
{
	if( m_ftpHandler )
	{
//		m_container->saveData();
		m_ftpHandler->ftpUpload();
		statusBar()->showMessage(tr("Uploading tasks config file to ftp"), 2000);
	}
}

void MainWindowImpl::saveUiSettings()
{	
	Settings::setValue( SettingsKeys::UI_WINDOW_POS , pos() );
	Settings::setValue( SettingsKeys::UI_WINDOW_SIZE, size() );
}

void MainWindowImpl::loadUiSettings()
{
	QPoint pos = Settings::value( SettingsKeys::UI_WINDOW_POS).toPoint();

    if( pos.x() == 0 )
        pos.setX(50);
    if( pos.y() == 0 )
        pos.setY(50);

	move( pos );
	QSize size =  Settings::value( SettingsKeys::UI_WINDOW_SIZE).toSize();
	qDebug() << size.width();
	qDebug() << size.height();
	resize(size);
};

//byebye
void MainWindowImpl::quit()
{		
    m_pTaskContainer->save("todo.xml");
	saveConfigSettings();
	saveTreeConfigSettings();    
}

//method used to sort tasks - should be removed or reimplemented - used during adding from internalization
int MainWindowImpl::compareItems(const QTreeWidgetItem& item1, const QTreeWidgetItem& item2)
{
    Q_ASSERT(false);
	int res = 0;
	int dateRes = 0, dateRes2 = 0;
    int pr1 = 0; //PriorityList.key(item1.text(0));
	int pr2 = 0;//PriorityList.key(item2.text(0));
	
	QDate currentDate = QDate::currentDate();

	if( pr1 < pr2 )
		return -1;//we've got higher priority here so get it on the top of the list
	else if( pr1 > pr2 )
		return 1;//continue to with next item
	else
	{
		dateRes = QDate::fromString(item1.text(2),DateFormat).daysTo(currentDate);
		dateRes2 = QDate::fromString(item2.text(2),DateFormat).daysTo(currentDate);

		res = dateRes -= dateRes2;
		if( res == 0) 
			return -1;//the same as next one, so should be on the top
		else return res; // continue with the next item
	}
}
//method used to sort tasks - should be removed or reimplemented - used during adding from internalization
int MainWindowImpl::sortedIndToInsert(const QTreeWidgetItem& item, QTreeWidget& tree)
{
	QTreeWidgetItem* treeItem;
	int i = 0;
	for(i = 0; i < tree.topLevelItemCount(); i++)
	{
		treeItem = tree.topLevelItem(i);
		if( compareItems(item, *treeItem) < 0 )
			return i;
	}
	return i;

}

//printing - should be reimplemented
void MainWindowImpl::printWork()
{
	if( m_pTreeWidget->topLevelItemCount() > 0 )
        Q_ASSERT_X(false, "printWork","reimplementthis");
//		print(m_pTree, tr("Work TODO"));
	else
		displayMsg( tr("Office task list is empty"));
}

/*
void MainWindowImpl::printBoth()
{
	if( m_pTree->topLevelItemCount() > 0 )
		print(m_pTree, tr("Work TODO"), true);
	else if( m_privateTasksTree->topLevelItemCount() > 0 )
		print(m_privateTasksTree, tr("Personal TODO"));
	else
		displayMsg(tr("Lists are empty"));
}

void MainWindowImpl::print(QTreeWidget* tree, QString title, bool both)
{

	if( !tree )
		return;

	QTextEdit* text = new QTextEdit(this);
	QTextCursor cursor(text->textCursor());
	cursor.movePosition(QTextCursor::Start);

	QTextCharFormat textFormat;
	QTextCharFormat boldFormat;
	boldFormat.setFontWeight(QFont::Bold);

	QTextFrame *topFrame = cursor.currentFrame();

	QTextTableFormat tableFormat;
	tableFormat.setBorder(1);
	tableFormat.setCellPadding(2);
	tableFormat.setCellSpacing(2);
	tableFormat.setAlignment(Qt::AlignLeft);
	QTextTable* table;
	
	
	int k = 1;
	if( both )
		k++;

	while( k > 0 )
	{
		if( both && k == 1 )
		{
			if( m_privateTasksTree->topLevelItemCount() > 0 )
			{
				title = tr("personall TODO");
				tree = m_privateTasksTree;
			}
			else
			{				
				printDocument(*text->document());
				delete text;
				return;
			}
		}
		//specify is office or personal
		cursor.insertBlock();
		cursor.insertText(title, boldFormat);	
		cursor.insertBlock();
		
		//draw table
		table = cursor.insertTable(tree->topLevelItemCount()+1, tree->columnCount(), tableFormat);
		
		cursor.setPosition( table->cellAt(0,0).firstCursorPosition().position());
		cursor.insertText(tr("Priority"), boldFormat);

		cursor.setPosition( table->cellAt(0,1).firstCursorPosition().position());
		cursor.insertText(tr("Task"), boldFormat);

		cursor.setPosition( table->cellAt(0,2).firstCursorPosition().position());
		cursor.insertText(tr("Date"), boldFormat);
		
		cursor.setPosition( table->cellAt(0,3).firstCursorPosition().position());
		cursor.insertText(tr("Percent"), boldFormat);

		QTreeWidgetItem* item;
		for( int i=1; i <= tree->topLevelItemCount(); i++)
		{
			item = tree->topLevelItem(i-1);
			for(int j = 0; j < tree->columnCount(); j++)
			{
				cursor.setPosition( table->cellAt(i,j).firstCursorPosition().position());
				cursor.insertText(item->text(j));
			}
		}
		cursor.setPosition(topFrame->lastPosition());
		cursor.insertBlock();
		k--;
	}

	QTextDocument *document = text->document();
	printDocument(*document);
	
	delete text;
}

void MainWindowImpl::printDocument(QTextDocument& document)
{
	QPrinter printer;

	QPrintDialog *dlg = new QPrintDialog(&printer, this);
	if (dlg->exec() != QDialog::Accepted)
	{		
        return;
	}

	document.print(&printer);
}
*/
void MainWindowImpl::keyPressEvent(QKeyEvent *keyPressed)
{
	switch( keyPressed->key() )
	{
	case Qt::Key_Delete:
	case Qt::Key_Backspace:
		{
			deleteTask();
		}
		break;
	}
}
//handle item list clicked here
void MainWindowImpl::treeItemClicked(QTreeWidgetItem* item ,int column)
{
    qDebug() << "Tree item Clicked";
    if( !ActionCollection::get("edit")->isEnabled())
    {
        ActionCollection::get("remove")->setEnabled(true);
        ActionCollection::get("edit")->setEnabled(true);
    }
    
    if( column == KTaskProgressColumn )
    {
        CustomProgressWidget* widget = qobject_cast<CustomProgressWidget*>(m_pTreeWidget->itemWidget(item, KTaskProgressColumn));
        m_pTaskContainer->setTaskProgress(widget->value(), item->text(KTaskProgressColumn).toInt());
    }
}

void MainWindowImpl::treeItemChanged(QTreeWidgetItem* pItem, int column)
{
    qDebug() << "treeItemChanged:" << column;
    if( column == KTaskTextColumn )
    {
        if(!m_MissEvent)
            m_pTaskContainer->editTask(pItem->text(KTaskTextColumn).toStdString(), pItem->text(KTaskIDColumn).toUInt());
        else
            m_MissEvent = false;
    }
}

void MainWindowImpl::setTaskProgress(int UID, int value )
{
    m_pTaskContainer->setTaskProgress(value, UID);
}

void MainWindowImpl::customContextMenuRequestedSlot(const QPoint& point) {
    qDebug()<< Q_FUNC_INFO;
    QPoint offset = m_pTreeWidget->mapToGlobal(QPoint(0,0));
    offset +=point;
    bool flag = (m_pTreeWidget->itemAt(point) != NULL );
    if( !flag )
    {
        m_pTreeWidget->setCurrentItem(NULL);
    }
    ActionCollection::get("remove")->setEnabled(flag);
    ActionCollection::get("edit")->setEnabled(flag);

    m_qpContextMenu->move(offset);
    m_qpContextMenu->show();
}


void MainWindowImpl::addTask()
{
    QTreeWidgetItem* parent = NULL;
    QTreeWidgetItem* item = NULL;
    QList<QTreeWidgetItem*> selected = m_pTreeWidget->selectedItems();
    m_MissEvent = true;
    if( !selected.isEmpty() )
    {
        parent = selected.at( 0 );
    }
    
    if( !parent )
    {
        item = new QTreeWidgetItem( m_pTreeWidget );        
    }
    else
    {
        item = new QTreeWidgetItem(parent);     
    }

    item->setSizeHint(KTaskProgressColumn, QSize(100, KRowHeight));    
    item->setFlags(item->flags() | Qt::ItemIsEditable );
    unsigned int pId = ( parent ? parent->text(KTaskIDColumn).toUInt() : 0 );
    pId = m_pTaskContainer->addTask("",0, pId);
    item->setText(KTaskIDColumn, QString::number(pId));
    m_pTreeWidget->setItemWidget(item, KTaskProgressColumn,constructItemWidget(*item));
    if( parent )
    {
        m_pTreeWidget->expandItem(parent);
        parent->addChild( item );
    }
    else
        m_pTreeWidget->addTopLevelItem( item );

    m_pTreeWidget->scrollToItem(item);
    m_pTreeWidget->editItem(item, KTaskTextColumn);
}

void MainWindowImpl::editTask()
{
    qDebug() << Q_FUNC_INFO;
	QList<QTreeWidgetItem*> selected = m_pTreeWidget->selectedItems();
    qDebug() << selected.size();
    if( !selected.isEmpty() )
    {
        m_pTreeWidget->editItem(selected.at( 0 ), KTaskTextColumn);
	}
	else
		displayMsg(tr("Task should be selected"));
}

void MainWindowImpl::deleteTask()
{
    QTreeWidgetItem* parent = NULL;
    QList<QTreeWidgetItem*> selected = m_pTreeWidget->selectedItems();
    if( !selected.isEmpty() )
    {
        parent = selected.at( 0 );
    }
    
    if( parent )
    {
        m_pTaskContainer->deleteTask(parent->text(KTaskIDColumn).toUInt());
        int ind = m_pTreeWidget->indexOfTopLevelItem( parent );
        if( ind == -1 )
        {
            //children selected;
            QTreeWidgetItem* realParent = parent->parent();
            realParent->removeChild( parent );
            delete parent;
        }
        else
        {            
            QList< QTreeWidgetItem* > children = parent->takeChildren();
            foreach( QTreeWidgetItem* item, children )
                delete item;
            
            m_pTreeWidget->takeTopLevelItem( m_pTreeWidget->indexOfTopLevelItem(parent));
            delete parent;
        }
    }
	else
		displayMsg(tr("Task should be selected"));
}


void MainWindowImpl::displayMsg(const QString& string)
{
	QMessageBox::warning(this, tr("QWhatToDo"), string, QMessageBox::Ok);
}

void MainWindowImpl::aboutQt()
{
	QMessageBox::aboutQt(this);
}

void MainWindowImpl::aboutQWhatToDo()
{
	QMessageBox::about(this, tr("About QWhatToDo"), tr("QWhatToDo is a simple application which allow... "));
}

void MainWindowImpl::synchronize()
{
/*TODO: 1.Download file from ftp server (if exist)
        1.a sync in container;
        1.b refresh tasks list
        2. upload fresh file
        */
}

void MainWindowImpl::ftpDone()
{
	QString info;
	if( m_ftpHandler->isDownloading())
	{
		info = tr("Downloading ");
		//as we done here, container should parse file and add to the list task which are not already on the list
//		m_container->loadData( DATAFILEFTP );
	}
	else
	{
		info = tr("Uploading ");
	}
	info += tr("todo config file finished successful");

	statusBar()->showMessage(info,5000);
}

void MainWindowImpl::ftpError(const QString& msg)
{
	QString info;
	if( m_ftpHandler->isDownloading())
		info = tr("Downloading ");
	else
		info = tr("Uploading ");

	info += tr("todo config file failed");
	info += "( " + msg + " )";

	statusBar()->showMessage(info,5000);
}

void MainWindowImpl::ftpProgress(qint64 done, qint64 total)
{
	QString info;
	if( m_ftpHandler->isDownloading())
		info = tr("Downloading... ");
	else
		info = tr("Uploading... ");

	int pr = (done * 100) / total;
	info += QString::number(pr);
	info +=" \%";

	statusBar()->showMessage(info,2000);
}
//EOF
